import React, { Component, PropTypes } from 'react';
import { Modal, message } from 'antd'
import ResizeTable from 'components/resize-table'
import SearchArea from 'components/search-area'
import httpFetch from 'share/httpFetch'
import { deepFullCopy } from "share/common";

class SelectorTree extends Component {

  onSelectChange = selectedRowKeys => {
    let { rowSelection } = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({ rowSelection });
  };

  onSelectItem = (record, selected) => {
    let { single, secondTableProps, tableProps } = this.props, { selectedData, data } = this.state;
    if (selected) {
      let temp = record;
      if (secondTableProps) {
        data.every(item => {
          let index = item[secondTableProps.key].findIndex(o => o[secondTableProps.props.rowKey] === record[secondTableProps.props.rowKey]);
          if (~index) {
            temp = deepFullCopy(item);
            delete temp[secondTableProps.key];
            temp = Object.assign(temp, item[secondTableProps.key][index]);
            return false
          }
          return true
        })
      }
      selectedData.push(temp);
      single && (selectedData = [temp]);
    } else {
      let key = secondTableProps ? secondTableProps.props.rowKey : tableProps.props.rowKey;
      selectedData.splice(selectedData.findIndex(item => item[key] === record[key]), 1);
    }
    this.setState({ selectedData });
  };

  onSelectAll = (selected, selectedRows, changeRows) => {
    changeRows.map(changeRow => this.onSelectItem(changeRow, selected))
  };

  state = {
    page: 0,
    data: [],
    loading: false,
    searchParams: {},
    pagination: {
      total: 0,
      defaultPageSize: 5
    },
    rowSelection: {
      selectedRowKeys: [],
      onChange: this.onSelectChange,
      onSelect: this.onSelectItem,
      onSelectAll: this.onSelectAll
    },
    selectedData: [],
    renderExpand: {}
  };

  componentWillReceiveProps = nextProps => {
    if(nextProps.visible === this.props.visible || !nextProps.visible){
      return;
    }
    const { rowSelection } = this.state, { single, selectedData, tableProps, secondTableProps } = nextProps;
    rowSelection.type = single ? 'radio' : 'checkbox';
    let res = [];
    selectedData.map(item => {
      res.push(secondTableProps ? item[secondTableProps.props.rowKey] : item[tableProps.props.rowKey]);
    });
    rowSelection.selectedRowKeys = res;
    let renderExpand = {};
    if (secondTableProps) {
      renderExpand.expandedRowRender = this.renderContent;
    }
    this.setState({ selectedData: selectedData, page: 0, rowSelection, renderExpand }, () => {
      this.getList();
      this.tableRef.refreshTableColumnsWidth(tableProps.props.columns);
    })
  };

  getList = () => {
    const { tableProps } = this.props, { page, searchParams } = this.state;
    this.setState({ loading: true });
    httpFetch.get(tableProps.url, Object.assign(searchParams, { page, size: 5 })).then(res => {
      this.setState({
        data: res.data,
        loading: false,
        pagination: {
          total: Number(res.headers['x-total-count']),
          current: page + 1,
          onChange: this.onChangePager,
          defaultPageSize: 5
        }
      });
    }).catch(e => {
      this.setState({ loading: false });
      message.error(e.response.data.message);
    })
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, () => {
        this.getList();
      })
  };

  search = values => {
    this.setState({ searchParams: values, page: 0 },() => {
      this.getList();
    })
  };

  clear = () => {
    this.setState({ searchParams: {}, page: 0 },() => {
      this.getList();
    })
  };

  handleOk = () => {
    const { onOk } = this.props, { selectedData } = this.state;
    onOk(selectedData);
  };

  renderContent = record => {
    const { secondTableProps } = this.props, { rowSelection } = this.state;
    return (
      <ResizeTable
        {...secondTableProps.props}
        rowSelection={rowSelection}
        pagination={false}
        dataSource={record[secondTableProps.key]}
      />
    )
  };

  render() {
    const { rowSelection, pagination, loading, data, selectedData, renderExpand } = this.state;
    const { title, visible, searchProps, tableProps, onCancel, secondTableProps } = this.props;
    return (
      <Modal
        title={title}
        onCancel={onCancel}
        onOk={this.handleOk}
        width={900}
        visible={visible}
      >
        <SearchArea
          {...searchProps}
          submitHandle={this.search}
          clearHandle={this.clear}
        />
        <div style={{ margin: '10px 0px' }}>
          共搜索到{pagination.total}条数据
        </div>
        <ResizeTable
          {...tableProps.props}
          loading={loading}
          rowSelection={ secondTableProps ? null : rowSelection }
          rowClassName={record => secondTableProps ?
            (selectedData.findIndex(item => item[tableProps.props.rowKey] === record[tableProps.props.rowKey]) > -1 ?
              'row-selected' : null)
            : null
          }
          pagination={pagination}
          dataSource={data}
          scrollY={270}
          onRef={tableRef => this.tableRef = tableRef}
          {...renderExpand}
        />
      </Modal>
    )
  }

  static proTypes = {
    title: PropTypes.string.isRequired,
    visible: PropTypes.bool,
    onOk: PropTypes.func,
    onCancel: PropTypes.func,
    tableProps: PropTypes.any, // 父表格属性 {url://获取数据的url, props: { columns ...}}
    searchProps: PropTypes.any, //searchForm, eventHandle等
    secondTableProps: PropTypes.any, // 相当于树的子节点属性（这里是表格嵌套中表格的属性），可以不填
    selectedData: PropTypes.array,
    single: PropTypes.bool,
    labelKey: PropTypes.string
  };

  static defaultProTypes = {
    single: false
  }
}

export default SelectorTree;
